import json

from csr_utils import log


class ErrorCode:
    errcode: int
    errmsg: str

    def __str__(self):
        return json.dumps(self.__package_dict(), ensure_ascii=False)

    @classmethod
    def __package_dict(cls):
        if not hasattr(cls, "errcode") or not hasattr(cls, "errcode"):
            log.error("Need 'errcode' and 'errmsg'")
            return {"errcode": None, "errmsg": None}
        return {"errcode": cls.errcode, "errmsg": cls.errmsg}

    @classmethod
    def package_response(cls, **kwargs):
        """
        构造返回结果
        """
        return {**cls.__package_dict(), **kwargs}


class SuccessCode(ErrorCode):
    errcode = 0
    errmsg = "OK"



class ValidationCode(ErrorCode):
    errcode = 400
    errmsg = "The request parameters do not meet the requirements !"


class ServerCode(ErrorCode):
    errcode = 500
    errmsg = "An error occurred inside the server !"


class AlreadyExistedCode(ErrorCode):
    errcode = 403
    errmsg = "The data already exists !"


class NotFoundCode(ErrorCode):
    errcode = 404
    errmsg = "The data you specified has been deleted or does not exist !"


class PermissionDeniedCode(ErrorCode):
    errcode = 401
    errmsg = "You do not have the authority to access this page!"


class FileOrDirDealError(Exception):

    def __init__(self, msg: str):
        super().__init__(self)  # 初始化父类
        self.errorinfo = msg

    def __str__(self):
        return self.errorinfo
